#!/usr/bin/env python3
"""
小红书内容推荐系统快速启动脚本
"""

import asyncio
import sys
import os
from datetime import datetime

# 添加项目路径
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from services.es_index_manager import ESIndexManager
from services.data_sync_service import DataSyncService
from services.es_client import ESClient
from services.recommendation_cache import RecommendationCache

class QuickStart:
    """快速启动管理器"""
    
    def __init__(self):
        self.es_manager = ESIndexManager()
        self.sync_service = DataSyncService()
        self.es_client = ESClient(use_async=True)
        self.cache_manager = RecommendationCache()
    
    async def check_dependencies(self):
        """检查依赖服务"""
        print("🔍 检查依赖服务...")
        
        # 检查ES连接
        es_health = await self.es_client.health_check()
        if es_health:
            print("✅ Elasticsearch连接正常")
        else:
            print("❌ Elasticsearch连接失败，请检查ES服务")
            return False
        
        # 检查Redis连接
        try:
            from config.redis import RedisUtils
            RedisUtils.set("health_check", "ok", 10)
            print("✅ Redis连接正常")
        except Exception as e:
            print(f"❌ Redis连接失败: {e}")
            return False
        
        # 检查MySQL连接
        try:
            from models import get_db
            db = next(get_db())
            db.execute("SELECT 1")
            print("✅ MySQL连接正常")
        except Exception as e:
            print(f"❌ MySQL连接失败: {e}")
            return False
        
        return True
    
    async def setup_elasticsearch(self):
        """设置Elasticsearch"""
        print("🔧 设置Elasticsearch...")
        
        # 创建索引
        success = self.es_manager.create_index()
        if success:
            print("✅ ES索引创建成功")
        else:
            print("❌ ES索引创建失败")
            return False
        
        return True
    
    async def sync_initial_data(self):
        """同步初始数据"""
        print("📊 同步初始数据...")
        
        # 同步已发布内容
        success = await self.sync_service.sync_published_contents(limit=100)
        if success:
            print("✅ 初始数据同步成功")
        else:
            print("❌ 初始数据同步失败")
            return False
        
        return True
    
    async def test_recommendation(self):
        """测试推荐功能"""
        print("🧪 测试推荐功能...")
        
        # 测试标签推荐
        recommendations = await self.es_client.tag_based_recommendation(
            user_tag_ids=[1, 3, 5],
            size=5
        )
        
        if recommendations:
            print(f"✅ 标签推荐测试成功，返回 {len(recommendations)} 条结果")
        else:
            print("⚠️ 标签推荐测试无结果（可能是数据不足）")
        
        # 测试文本相似推荐
        similar_recs = await self.es_client.text_similarity_recommendation(
            content_id=1,
            size=5
        )
        
        if similar_recs:
            print(f"✅ 文本相似推荐测试成功，返回 {len(similar_recs)} 条结果")
        else:
            print("⚠️ 文本相似推荐测试无结果（可能是数据不足）")
        
        return True
    
    async def setup_cache(self):
        """设置缓存"""
        print("💾 设置缓存...")
        
        # 测试缓存功能
        test_data = [
            {"content_id": 1, "title": "测试内容", "score": 0.9}
        ]
        
        await self.cache_manager.cache_user_recommendations(
            user_id=999,  # 测试用户ID
            page=1,
            recommendations=test_data
        )
        
        cached_data = await self.cache_manager.get_user_recommendations(
            user_id=999,
            page=1
        )
        
        if cached_data:
            print("✅ 缓存功能测试成功")
        else:
            print("❌ 缓存功能测试失败")
            return False
        
        return True
    
    async def run_startup(self):
        """运行启动流程"""
        print("🚀 小红书内容推荐系统快速启动")
        print("=" * 50)
        
        start_time = datetime.now()
        
        # 1. 检查依赖
        if not await self.check_dependencies():
            print("❌ 依赖检查失败，请检查服务状态")
            return False
        
        # 2. 设置ES
        if not await self.setup_elasticsearch():
            print("❌ ES设置失败")
            return False
        
        # 3. 同步数据
        if not await self.sync_initial_data():
            print("❌ 数据同步失败")
            return False
        
        # 4. 测试推荐
        await self.test_recommendation()
        
        # 5. 设置缓存
        if not await self.setup_cache():
            print("❌ 缓存设置失败")
            return False
        
        end_time = datetime.now()
        duration = (end_time - start_time).total_seconds()
        
        print("=" * 50)
        print("🎉 启动完成！")
        print(f"⏱️ 耗时: {duration:.2f} 秒")
        print("📝 接下来可以:")
        print("   1. 启动后端服务: python main.py")
        print("   2. 访问API文档: http://localhost:8000/docs")
        print("   3. 测试推荐接口: http://localhost:8000/api/recommendations")
        print("=" * 50)
        
        return True

async def main():
    """主函数"""
    quick_start = QuickStart()
    
    try:
        success = await quick_start.run_startup()
        if success:
            print("✅ 系统启动成功！")
        else:
            print("❌ 系统启动失败！")
            sys.exit(1)
    except Exception as e:
        print(f"❌ 启动过程中发生错误: {e}")
        sys.exit(1)
    finally:
        # 清理资源
        await quick_start.es_client.close()

if __name__ == "__main__":
    asyncio.run(main())
